<?php

/**
 * 在万网的接口读取whois信息
 * @param type $domain
 * @param type $realtime
 * @return type
 */
function whois_hichina($domain, $realtime = false, $timecache = 300000) {
    $arr = explode('.', $domain);
    $length = count($arr);
    $extk = $length - 1;
    $dok = $length - 2;
    $maindomain = $arr[$dok] . '.' . $arr[$extk];
    if (!in_array($arr[$extk], array('com', 'cn', 'net', 'org', 'info', 'cc'))) {
        log::n('php whois[' . $domain . '],ext not allow');
        return array('regdate' => '2013-01-01', 'expdate' => '2030-01-01', 'dnsserver' => 'Other Ext', 'exp_date' => '2030-01-01', 'dns_server' => 'Other Ext');
    }
    #Cache存放路径
    $DomainInfoCacheFile = APP_ROOT_DIR . '/data/whois-cache/hichina/' . substr(md5($maindomain), 0, 2) . '/' . $maindomain . '.txt';
    if (!$realtime && (file_exists($DomainInfoCacheFile) && time() - filemtime($DomainInfoCacheFile) < $timecache)) {
        $json = file_get_contents($DomainInfoCacheFile);
        $arrDomainInfo = json_decode($json, true);
        log::n('cache whois[' . $domain . ']');
        if ($arrDomainInfo['exp_date']) {
            return $arrDomainInfo;
        }
    }
    #反之去接口查询数据
    $whoisurl = 'http://whois.hichina.com/whois/api_whois?host=' . $maindomain . '&oper=0';
    $s = curl_string($whoisurl);
    log::n('realtime whois[' . $domain . ']');
    if (!$s) {
        return false;
    }
    $arrDomainInfo = json_decode($s, true);
    foreach ($arrDomainInfo as &$item) {
        $item = trim($item);
    }unset($item);

    $dns = explode(',', trim($arrDomainInfo['name_server']));
    $arrDomainInfo['exp_date'] = preg_replace('#\s+#', '', $arrDomainInfo['exp_date']);
    $arrDomainInfo['reg_date'] = preg_replace('#\s+#', '', $arrDomainInfo['reg_date']);
    $arrDomainInfo['dns_server'] = $dns[0];
    if ($arrDomainInfo['name'] != $maindomain || empty($arrDomainInfo['status'])) {
        log::w('get whois info failed,domain[' . $maindomain . ']');
        return false;
    }
    FCheckDir($DomainInfoCacheFile);
    file_put_contents($DomainInfoCacheFile, json_encode($arrDomainInfo));
    return $arrDomainInfo;
}

?>